import React, { useState, useEffect } from 'react';
import { render } from 'ink';
import { configManager } from '../services/config';
import { Message, AppConfig, ConnectionStatus, ThemeConfig } from '../types';
import ChatInterface from './ChatInterface';

interface AppProps {
  autoQuestion?: string;
}

interface AppState {
  messages: Message[];
  config: AppConfig | null;
  connectionStatus: ConnectionStatus;
  theme: ThemeConfig;
}

const defaultTheme: ThemeConfig = {
  userMessage: 'cyan',
  aiMessage: 'white', 
  systemMessage: 'yellow',
  errorMessage: 'red',
  codeBlock: 'gray',
  inputArea: 'blue'
};

const App: React.FC<AppProps> = ({ autoQuestion }) => {
  const [state, setState] = useState<AppState>({
    messages: [],
    config: null,
    connectionStatus: { connected: false, retrying: false },
    theme: defaultTheme
  });

  useEffect(() => {
    // 初始化配置
    const initializeApp = async () => {
      try {
        const config = await configManager.loadConfig();
        setState(prev => ({
          ...prev,
          config,
          connectionStatus: { connected: true, retrying: false }
        }));
      } catch (error) {
        setState(prev => ({
          ...prev,
          connectionStatus: { 
            connected: false, 
            retrying: false,
            error: error instanceof Error ? error.message : '配置加载失败'
          }
        }));
      }
    };

    initializeApp();
  }, []);

  const addMessage = (message: Omit<Message, 'id' | 'timestamp'>) => {
    const newMessage: Message = {
      ...message,
      id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, // 确保唯一性
      timestamp: new Date()
    };

    setState(prev => ({
      ...prev,
      messages: [...prev.messages, newMessage]
    }));

    return newMessage.id;
  };

  const updateMessage = (id: string, updates: Partial<Message>) => {
    setState(prev => ({
      ...prev,
      messages: prev.messages.map(msg => 
        msg.id === id ? { ...msg, ...updates } : msg
      )
    }));
  };

  const clearMessages = () => {
    setState(prev => ({
      ...prev,
      messages: []
    }));
  };

  return (
    <ChatInterface
      messages={state.messages}
      config={state.config}
      connectionStatus={state.connectionStatus}
      theme={state.theme}
      onAddMessage={addMessage}
      onUpdateMessage={updateMessage}
      onClearMessages={clearMessages}
      autoQuestion={autoQuestion}
    />
  );
};

export default App;